//app.j
var util = require('/utils/utils.js');
var api = require('/utils/interface.js');
App({
  onLaunch: function() {
    var that = this;
    //登录
    wx.login({
      success: function(res) {
        that.Post(api.wxapp.loginby_code, {
          code: res.code
        }, function(res) {
          if (res.code == 1) {
            that.globalData.openId = res.data.OpenId;
            var token = wx.getStorageSync('userToken');
            if (token == '') {
              // 获取用户信息
              wx.getSetting({
                success: res => {
                  if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getUserInfo({
                      success: res => {
                        // 可以将 res 发送给后台解码出 unionId
                        that.globalData.userInfo = res.userInfo;
                        that.globalData.encryptedData = res.encryptedData;
                        that.globalData.iv = res.iv;
                        that.Post(api.wxapp.re_wx_user_info, {
                          openId: that.globalData.openId,
                          nickName: that.globalData.userInfo.nickName,
                          avatarUrl: that.globalData.userInfo.avatarUrl,
                          sex: that.globalData.userInfo.gender,
                          iv: that.globalData.iv
                        }, function(res1) {
                          if (res1.code == 1) {
                            that.globalData.token = res1.data.Token;
                            wx.setStorageSync('userToken', res1.data.Token);
                          }
                        });
                      }
                    });
                  }
                }
              });
            } else {
              
             
            }
          } else {
            console.log(res);
          }
        });
      }
    });
  },
  //写入用户信息
  writeUserInfo: function(user) {
    // wx.setStorageSync(key, data);
    var that = this;
    that.globalData.userInfo = user;
  },
  globalData: {
    userInfo: null,
    encryptedData: "",
    iv: "",
    userid: "",
    token: "",
    openId: "",
    domain: "http://47.105.41.175:8090/"
  },
  storageKey: {
    userInfo: "userInfo"
  },
  getToken: function() {
    var that = this;
    that.Post(api.wxapp.get_wx_user_info, {
      openId: that.globalData.openId,
      encryptedData: that.globalData.encryptedData,
      iv: that.globalData.iv
    }, function(res) {
      if (res.Code == 1) {
        that.globalData.token = res.data.Token;
        wx.setStorageSync('userToken', res.data.Token);
      }
      // else {
      //   that.WxAlert(res.msg);
      // }
    });
  },
  //登录
  get_user_info: function(res0, complete) {
    console.log(1);
    var app = getApp();
    var that = this;
    var rDetail = res0.detail;
    console.log(2);
    //拒绝授权
    if (rDetail.errMsg == "getUserInfo:fail auth deny") {
      console.log("用户拒绝授权");
      return;
    }
    console.log(3);
    //将用户存全局变量
    app.globalData.userInfo = rDetail.userInfo;
    app.globalData.encryptedData = rDetail.encryptedData;
    app.globalData.iv = rDetail.iv;
    wx.setStorageSync("userInfo", rDetail.userInfo);
    console.log(rDetail.userInfo);
    console.log(4);
    //登录获取code
    wx.login({
      success: function(rt) {
        console.log(5);
        console.log(rt);
        app.Post(api.wxapp.loginby_code, {
          code: rt.code
        }, function(res) {
          console.log(6);
          console.log(res);
          if (res.code == 1) {
            app.globalData.openId = res.data.OpenId;
            //获取
            console.log(7);
            app.Post(api.wxapp.re_wx_user_info, {
              openId: res.data.OpenId,
              nickName: rDetail.userInfo.nickName,
              avatarUrl: rDetail.userInfo.avatarUrl,
              sex: rDetail.userInfo.gender,
              iv: app.globalData.iv
            }, function(res1) {
              console.log(8);
              if (res1.code == 1) {
                that.globalData.token = res1.data.Token;
                wx.setStorageSync('userToken', res1.data.Token);
                that.Post(api.wxapp.loginby_utk, {}, function (res) {
                  if (res.code == 1) {
                    complete(res1.data.Token);
                    that.globalData.userInfo = res.data.User;
                  }
                });
              }
              
            });
          } else {
            app.WxAlert(res.msg);
          }
        });
      }
    });
  },
  //封装请求
  WxRequest: function(url, method, param, success, fail, complete) {
    var that = this;
    if (param) {
      param.token = wx.getStorageSync('userToken');
    }
    wx.request({
      url: url,
      data: param,
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: method,
      success: function(res) {
        if (typeof success == "function") {
          if (res.data.code != 3) {
            success(res.data);
          } else {
            wx.redirectTo({
              url: '/pages/auth/auth',
            })
          }
        }
      },
      fail: function() {
        if (typeof fail == "function") {
          fail();
        }
      },
      complete: function() {
        if (typeof complete == "function") {
          complete();
        }
      }
    });
  },
  //POST
  Post: function(url, param, success, fail, complete) {
    var that = this;
    that.WxRequest(url, "POST", param, success, fail, complete);
  },
  //GET
  Get: function(url, param, success, fail, complete) {
    var that = this;
    that.WxRequest(url, "GET", param, success, fail, complete);
  },
  //系统公共提示
  WxAlert: function(content) {
    wx.showModal({
      title: '系统提示',
      content: content,
      success: function(res) {
        if (res.confirm) {
          //console.log('用户点击确定')
        } else {
          //console.log('用户点击取消')
        }
      }
    });
  },
  //成功提示
  ShowMsg: function(msg, complete) {
    wx.showToast({
      title: msg,
      icon: 'success',
      duration: 2000,
      complete: complete
    });
  },
  //多张图片上传
  uploadimg: function(data) {
    var that = this,
      i = data.i ? data.i : 0, //当前上传的哪张图片
      success = data.success ? data.success : 0, //上传成功的个数
      fail = data.fail ? data.fail : 0; //上传失败的个数
    var imgs = data.imgs ? data.imgs : [];
    wx.uploadFile({
      url: api.wxapp.UploadFiles,
      filePath: data.path[i],
      name: 'file', //这里根据自己的实际情况改
      formData: null, //这里是上传图片时一起上传的数据
      success: (resp) => {
        success++; //图片上传成功，图片上传成功的变量+1
        console.log(resp)
        console.log(i);
        var json = JSON.parse(resp.data);
        imgs.push(json.data.FileWebPath[0]);
        //这里可能有BUG，失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时，这里的success才+1
        data.imgs = imgs;
        i++; //这个图片执行完上传后，开始上传下一张
        if (i == data.path.length) { //当图片传完时，停止调用          
          console.log('执行完毕');
          console.log('成功：' + success + " 失败：" + fail);
          console.log(imgs);
          data.com(data);
        } else { //若图片还没有传完，则继续调用函数
          console.log(i);
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      },
      fail: (res) => {
        fail++; //图片上传失败，图片上传失败的变量+1
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        console.log(i);
       
        }
    });
  }

})